package com.power.web.action.group;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.power.Constants;
import com.power.model.group.TiGroup;
import com.power.model.user.TsSysuser;
import com.power.services.group.TiGroupService;
import com.power.util.CharacterUtil;
import com.power.util.DateJsonValueProcessor;
import com.power.util.DateTimeUtil;
import com.power.util.FileUtil;
import com.power.util.PingYinUtil;
import com.power.util.RequestUtil;
import com.power.util.XmlUtil;
import com.power.web.action.base.AbstractBaseAction;

public class TiGroupAction extends AbstractBaseAction
{

  @Autowired
  @Qualifier("tiGroupService")
  private TiGroupService tiGroupService;
  private int flag;
  private  TiGroup group;
  private String jsonString;
  private File videoFile;
  private String videoFileFileName;
  @SuppressWarnings("unchecked")
  public String buildJSONString() {
      try {
          int start = this.start;
          int limit = this.limit;
          if (limit == 0)
              limit = 20;
          String  groupName=CharacterUtil.encode(RequestUtil.getParam(request, "groupName", ""));
          Integer hid = RequestUtil.getParam(request, "hid", -1);
          Integer did = RequestUtil.getParam(request, "did", -1);
          Map<String, Object> map = this.tiGroupService.findAll(groupName, start,
                  limit, hid,did);
          List<TiGroup> list = (List<TiGroup>) map.get("data");
          int count = new Integer(map.get("count").toString());
          StringBuffer _JSONStr = null;
          String callback = this.callback;
          _JSONStr = new StringBuffer();
          _JSONStr.append(callback).append("({\"total\":").append(count)
                  .append(",\"results\":");
          JsonConfig cfg = new JsonConfig();
          cfg.registerJsonValueProcessor("inputDate",
                  new DateJsonValueProcessor("yyyy-MM-dd kk:mm:ss"));
          cfg.registerJsonValueProcessor(java.util.Date.class,
                  new DateJsonValueProcessor("yyyy-MM-dd"));
          cfg.registerJsonValueProcessor(java.sql.Date.class,
                  new DateJsonValueProcessor("yyyy-MM-dd"));
          JSONArray jsonObject = JSONArray.fromObject(list, cfg);
          _JSONStr.append(jsonObject.toString());
          _JSONStr.append("})");
          jsonString = _JSONStr.toString();
      } catch (Exception e) {
          log.error("加载小组信息列表出错", e);
          this.jsonString = "[]";
      }
      return Constants.JSONSTRING_RESULT_NAME;
  }

  public String delete() throws Exception
  {
    String id = RequestUtil.getParam(this.request, "deleteID", "");
    String[] ids = id.split("_");
    try {
        this.response.setCharacterEncoding("UTF-8");
    for (int i = 0; i < ids.length; i++) {
        TiGroup group = this.tiGroupService.read(new Integer(ids[i]));
        this.tiGroupService.delete(group);
    }
      this.response.getWriter().print("{success:true,msg:'删除成功!'}");
    } catch (Exception e) {
      log.error("输出JSON数据错误！", e);
      this.response.getWriter().print("{failure:true,msg:'删除失败!'}");
    }
    return null;
  }

  
  public String saveOrUpdate() {
      this.response.reset();
      this.response.setCharacterEncoding("UTF-8");
      try {
          if(null != group){
              
              if (null != videoFile) {
                  String   basePath = request.getSession().getServletContext()
                          .getRealPath("/");
                  String   compressPath = XmlUtil.getValue("imgPath",
                          "sysConfig")
                          + "/";
                  String   fileName = new Date().getTime()
                          + videoFileFileName.substring(videoFileFileName
                                  .lastIndexOf("."));
                  if (FileUtil.doUpFile(basePath + compressPath + fileName,
                      videoFile)) {
                      group.setVideosrc(compressPath + fileName);
                  }
              }
              
              TsSysuser user = (TsSysuser) this.session.get(Constants.USERINFO_KEY);
              group.setInputDate(DateTimeUtil.getCurrentDateTime());
              group.setInputMan(user.getUsername());
              group.setInputManId(user.getId());
              tiGroupService.saveOrUpdate(group);
          }
          this.response.getWriter().print("{success:true,msg:'保存成功!'}");
      } catch (Exception e) {
          log.error("小组信息保存失败", e);
          try {
              this.response.getWriter().print("{success:false,msg:'保存失败!'}");
          } catch (IOException e1) {
              e1.printStackTrace();
          }
      }
      return null;
  }
  
  public String save() {
      this.response.reset();
      this.response.setCharacterEncoding("UTF-8");
          if (null != group) {
                  if (null != videoFile) {
                      String   basePath = request.getSession().getServletContext()
                              .getRealPath("/");
                      String   compressPath = XmlUtil.getValue("imgPath",
                              "sysConfig")
                              + "/";
                      String   fileName = new Date().getTime()
                              + videoFileFileName.substring(videoFileFileName
                                      .lastIndexOf("."));
                      if (FileUtil.doUpFile(basePath + compressPath + fileName,
                          videoFile)) {
                          group.setVideosrc(compressPath + fileName);
                      }
                  }
              
              TsSysuser user = (TsSysuser) this.session
                      .get(Constants.USERINFO_KEY);
              group.setInputDate(DateTimeUtil.getCurrentDateTime());
              group.setInputMan(user.getUsername());
              group.setInputManId(user.getId());
              group.setFullChar(PingYinUtil.getPingYin(group.getName(), 1, 1));
              group.setFirstChar(PingYinUtil.getPingYin(group.getName(), 2, 1).substring(0,1));
          }
          try {
              tiGroupService.saveOrUpdate(group);
              request.setAttribute("ifsuccess", "保存成功!");
          } catch (RuntimeException e) {
              request.setAttribute("ifsuccess", "保存失败!");
              e.printStackTrace();
          }
      return "ifsuccess";
  }
  
  public String showPage() {
      Integer hid = RequestUtil.getParam(request, "hid", 0);
      Integer did = RequestUtil.getParam(request, "did", 0);
      Integer gid = RequestUtil.getParam(request, "gid", 0);
      try {
          if (gid == 0) {
              group = new TiGroup();
              group.setDeleteFlag("0");
              group.setHid(hid);
              group.setDid(did);
          } else {
              group = tiGroupService.read(gid);
          }
      } catch (Exception e) {
          log.error("获取数据错误");
          e.printStackTrace();
      }
      return "showPage";
  }

  public String read(){
      int id = RequestUtil.getParam(this.request, "id", -1);
      group = this.tiGroupService.read(new Integer(id));
      return "showgroup";
  }

  public String execute()
  {
    return null;
  }

  @SuppressWarnings("unchecked")
  public String loadByDepartment() {
      this.response.reset();
      this.response.setCharacterEncoding("UTF-8");
      PrintWriter out = null;
      List<TiGroup> list = new ArrayList<TiGroup>();
      try {
          out = response.getWriter();
          Integer did = RequestUtil.getParam(request, "did", -1);
          if (did != -1) {
              Map<String, Object> map = this.tiGroupService.findComboxAll("",
                      start, limit, did);
              list = (List<TiGroup>) map.get("data");
          }
          String callback = RequestUtil.getParam(this.request, "callback",
                  "callback");
          StringBuffer _JSONStr = new StringBuffer();
          _JSONStr.append(callback).append("([");
          for (int i = 0; i < list.size(); ++i) {
              TiGroup obj = (TiGroup) list.get(i);
              _JSONStr.append("[\"").append(obj.getId()).append("\",");
              _JSONStr.append("\"").append(obj.getName()).append("\"],");
          }
          if (list.size() > 0)
              _JSONStr.deleteCharAt(_JSONStr.lastIndexOf(","));
          _JSONStr.append("])");
          this.jsonString = _JSONStr.toString();
          out.print(this.jsonString);
      } catch (Exception e) {
          log.error("加载单位出错", e);
          out.print("[]");
      }
      return null;
  }

public String getJsonString() {
    return jsonString;
}

public void setJsonString(String jsonString) {
    this.jsonString = jsonString;
}

public TiGroup getGroup() {
    return group;
}

public void setGroup(TiGroup group) {
    this.group = group;
}

public int getFlag() {
    return flag;
}

public void setFlag(int flag) {
    this.flag = flag;
}

public File getVideoFile() {
    return videoFile;
}

public void setVideoFile(File videoFile) {
    this.videoFile = videoFile;
}

public String getVideoFileFileName() {
    return videoFileFileName;
}

public void setVideoFileFileName(String videoFileFileName) {
    this.videoFileFileName = videoFileFileName;
}

}